package com.mercury.api;

import com.alibaba.fastjson.JSONObject;
import com.mercury.entity.*;
import com.mercury.service.*;
import com.mercury.tools.WeChat;
import io.swagger.annotations.*;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("invoke")
@Api("Swagger-IndexController")
public class IndexController {
    private static String WeChatAppID = "wxcf6fe3913ff1cf68";

    private final
    PcorderService pcorderService;

    private final
    PcclassinfoService pcclassinfoService;

    private final
    PcschoolinfoService pcschoolinfoService;

    private final
    PcclassroominfoService pcclassroominfoService;

    private final
    PcuserinfoService pcuserinfoService;

    private final
    PcattendanceService pcattendanceService;

    private final
    PcgiftaddressService pcgiftaddressService;

    private final
    PaintingsService paintingsService;

    @Autowired
    public IndexController(PcorderService pcorderService,
                           PcclassinfoService pcclassinfoService,
                           PcschoolinfoService pcschoolinfoService,
                           PcclassroominfoService pcclassroominfoService,
                           PcuserinfoService pcuserinfoService,
                           PcattendanceService pcattendanceService,
                           PcgiftaddressService pcgiftaddressService,
                           PaintingsService paintingsService
    ) {
        this.pcorderService = pcorderService;
        this.pcclassinfoService = pcclassinfoService;
        this.pcschoolinfoService = pcschoolinfoService;
        this.pcclassroominfoService = pcclassroominfoService;
        this.pcuserinfoService = pcuserinfoService;
        this.pcattendanceService = pcattendanceService;
        this.pcgiftaddressService = pcgiftaddressService;
        this.paintingsService = paintingsService;
    }

    /**
     * 微信获取token
     *
     * @param wxInfo
     * @return
     */
    @RequestMapping(value = "/getTicKet", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getTicKet(@RequestBody WxInfo wxInfo) {
        JSONObject result = new JSONObject();
        long wx_timestamp = WeChat.CreatenTimestamp();
        String wx_token = WeChat.getAccessToken();
        String wx_ticker = WeChat.getTicKet(wx_token);
        String appId = WeChatAppID;

        //long timestamp = wx_timestamp;
        String nonceStr = "wego";
        String signature = WeChat.CheckSignature(wx_ticker, wx_timestamp, wxInfo.getUrl());
        WxInfo info = new WxInfo();
        info.setAppId(appId);
        info.setTicker(wx_ticker);
        info.setNonceStr(nonceStr);
        info.setSignature(signature);
        info.setTimestamp(wx_timestamp);
        info.setUrl(wxInfo.getUrl());
        result.put("IsSuccess", true);
        result.put("Data", info);
        return result.toString();
    }

    @RequestMapping(value = "/GetOpenId", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String GetOpenId(@RequestBody JSONObject jsonObject) {
        WxInfo info = new WxInfo();
        info.setOpenid(WeChat.GetOpenId(jsonObject.getString("Code")));
        JSONObject json = new JSONObject();
        json.put("Data", info);
        json.put("IsSuccess", true);
        System.out.println("GetOpenId result ===>" + json.toString());
        return json.toString();
    }

    @RequestMapping(value = "/PreCheckBuy", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String PreCheckBuy(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        if (pcclassroominfoService.PreCheckBuy(json)) {
            result.put("IsSuccess", true);
        } else {
            result.put("IsSuccess", false);
            result.put("ErrorMessage", "对不起，该课室名额已售完，请选择其他课室");
        }
        return result.toString();
    }

    @RequestMapping(value = "/WxPay", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String WxPay(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        result.put("IsSuccess", true);
        String fee = String.valueOf((int) (json.getDouble("fee") * 100));

        System.out.println("微信下单json：" + json);

        result.put("Data", WeChat.GetUnifiedOrderResult(
                json.getString("itemname"),
                json.getString("attach"),
                json.getString("openid"),
                fee)
        );
        return result.toString();
    }

    @RequestMapping(value = "/GetOrderByQuery", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String GetOrderByQuery(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        System.out.println("GetOrderByQuery request ===>" + json.toJSONString());
        if ("".equals(json.getString("WxOpenID")) && "".equals(json.getString("Name")) && "".equals(json.getString("ContactTel"))) {
            result.put("IsSuccess", true);
        } else {
            List<OrderSO> orders = pcorderService.GetOrderDetail(json);
            result.put("IsSuccess", true);
            if (orders.size() > 0) {
                result.put("Data", orders.get(0));
            }
        }
        return result.toString();
    }

    /**
     * 微信用户授权
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/GetOAuth", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String GetOAuth(HttpServletRequest request) {
        JSONObject result = new JSONObject();
        result.put("IsSuccess", true);
        result.put("ErrorMessage", WeChat.Getoauth(request));
        return result.toString();
    }

    /**
     * 获取课程列表
     *
     * @param json
     * @return
     */
    @RequestMapping(value = "/GetStdClassName", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String GetStdClassName(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        result.put("Datas", pcclassinfoService.SearchPcclassinfos(json));
        return result.toString();
    }

    /**
     * 获取校区列表
     *
     * @param json
     * @return
     */
    @RequestMapping(value = "/GetStdSchoolName", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String GetStdSchoolName(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        result.put("Datas", pcschoolinfoService.SearchPcschoolinfos(json));
        return result.toString();
    }

    @RequestMapping(value = "/getClassDate", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getClassDate(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        result.put("Datas", pcclassroominfoService.searchTimeCate(json));
        return result.toString();
    }

    @RequestMapping(value = "/GetClassTime", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String GetClassTime(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        result.put("Datas", pcclassroominfoService.searchTime(json));
        return result.toString();
    }

    /**
     * 获取教室列表
     *
     * @param json
     * @return
     */
    @RequestMapping(value = "/GetStdClassRoom", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String GetStdClassRoom(@RequestBody JSONObject json) {
        json.put("AvailableVolume", 0);
        JSONObject result = new JSONObject();
        List<Pcclassroominfo> list = pcclassroominfoService.SearchAvailablePcclassroominfos(json);
        List<Pcclassroominfo> returns = new ArrayList<Pcclassroominfo>();

        if (list != null && list.size() > 0) {
            for (Integer i = 0; i < list.size(); i++) {
                Pcclassroominfo item = list.get(i);
                if (item.getAvailableVolume() > 0) {
                    returns.add(item);
                }
            }
        }

        result.put("Datas", returns);
        return result.toString();
    }

    /**
     * 获取订单信息
     *
     * @param json
     * @return
     */
    @RequestMapping(value = "/GetBillInfo", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String GetBillInfo(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        result.put("IsSuccess", true);
        result.put("Data", pcclassroominfoService.GetBillInfo(json));
        return result.toString();
    }

    /**
     * 微信回调通知地址
     *
     * @param xml
     * @return
     */
    @RequestMapping(value = "/WxResultNotify", method = {RequestMethod.POST, RequestMethod.GET}, produces = MediaType.TEXT_XML_VALUE)
    @ResponseBody
    public String WxResultNotify(@RequestBody WxPayResult xml) {

        System.out.println("WxResultNotify" + xml.getTransaction_id());

        Document result = DocumentHelper.createDocument();
        Element root = result.addElement("xml");
        if (xml.getTransaction_id() == null) {
            root.addElement("return_code").addCDATA("FAIL");
            root.addElement("return_msg").addCDATA("支付结果中微信订单号不存在");
            return result.asXML();
        }
        if (!WeChat.QueryOrder(xml.getTransaction_id())) {
            root.addElement("return_code").addCDATA("FAIL");
            root.addElement("return_msg").addCDATA("订单查询失败");
            return result.asXML();
        }
        pcorderService.create(xml);
        root.addElement("return_code").addCDATA("SUCCESS");
        root.addElement("return_msg").addCDATA("OK");
        return result.asXML();
    }

    @RequestMapping(value = "/SaveOrder", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String SaveOrder(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        pcorderService.create(json);
        result.put("IsSuccess", true);
        return result.toString();
    }

    @RequestMapping(value = "/GetCode", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Pcuserinfo GetCode(@RequestBody JSONObject json) {
        return pcuserinfoService.getUserinfo(json);
    }

    @RequestMapping(value = "/getAttendance", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getAttendance(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        try {
            List<Pcattendance> list = pcattendanceService.getAttendanceListByOrderId(json);
            result.put("IsSuccess", true);
            result.put("Datas", list);
        } catch (Exception ex) {
            result.put("IsSuccess", false);
            result.put("ErrorMessage", "处理失败，请重试");
            result.put("StackTrace", ex.toString());
        }
        return result.toString();
    }


    @RequestMapping(value = "/createAttendance", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String createAttendance(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        try {
            Pcorder order = pcorderService.getOrderById(json);

            JSONObject soAttList = new JSONObject();
            soAttList.put("orderId", order.getGuid());
            List<Pcattendance> list = new ArrayList<Pcattendance>(pcattendanceService.getAttendanceListByOrderId(soAttList));


            if (list.size() == 0) {
                pcattendanceService.createPcattendance(order);
                result.put("IsSuccess", true);
            } else {
                Pcattendance latestItem = list.get(0);
                boolean isToday = isToday(latestItem.getCreateTime().getTime(), "yyyy-MM-dd");
                if (isToday) {
                    result.put("IsSuccess", false);
                    result.put("ErrorMessage", "今日已签到");
                } else {
                    pcattendanceService.createPcattendance(order);
                    result.put("IsSuccess", true);
                }
            }
        } catch (Exception ex) {
            result.put("IsSuccess", false);
            result.put("ErrorMessage", "处理失败，请重试");
            result.put("StackTrace", ex.toString());
        }
        return result.toString();
    }


    @RequestMapping(value = "/getGiftAddress", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getGiftAddress(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        try {
            String openid = json.getString("openId");
            Pcgiftaddress model = pcgiftaddressService.getAddressByOpenId(openid);
            result.put("IsSuccess", true);
            if (model != null) {
                result.put("Data", model);
            }
        } catch (Exception ex) {
            result.put("IsSuccess", false);
            result.put("ErrorMessage", "处理失败，请重试");
            result.put("StackTrace", ex.toString());
        }
        return result.toString();
    }


    @RequestMapping(value = "/createGiftAddress", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String createGiftAddress(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        try {
            String openid = json.getString("openId");
            Pcgiftaddress model = pcgiftaddressService.getAddressByOpenId(openid);
            if (model == null) {
                pcgiftaddressService.create(json);
                result.put("IsSuccess", true);
            } else {
                result.put("IsSuccess", false);
                result.put("ErrorMessage", "请不要重复提交领奖信息");
            }
        } catch (Exception ex) {
            result.put("IsSuccess", false);
            result.put("ErrorMessage", "处理失败，请重试");
            result.put("StackTrace", ex.toString());
        }
        return result.toString();
    }

    @RequestMapping(value = "/queryByAuthor", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String queryByAuthor(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        List list = paintingsService.queryByAuthor(json);
        if (list.size() > 0) {
            result.put("IsSuccess", true);
            result.put("Datas", list);
        } else {
            result.put("IsSuccess", false);
        }
        return result.toString();
    }

    @RequestMapping(value = "/queryAllPaintings", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String queryAllPaintings() {
        JSONObject result = new JSONObject();
        List list = paintingsService.queryAllPaintings();
        result.put("IsSuccess", true);
        result.put("Datas", list);
        return result.toString();
    }

    ///内部方法
    private static boolean isToday(long time, String pattern) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String param = sdf.format(date);//参数时间
        String now = sdf.format(new Date());//当前时间
        return param.equals(now);
    }

}
